﻿using System.Security.Cryptography;
using System.Threading.Tasks;
using Wx.Sdk.App.Entity;
using Wx.Sdk.Ext;
using Wx.Sdk.Utils;

namespace Wx.Sdk.App.Src
{
    public class AppLogin : IAppLogin
    {
        WxApp wxApp;
        public AppLogin(WxApp wxApp) {
            this.wxApp = wxApp;
        }
        AppUser IAppLogin.DeCodeUserInfo(RawData rawData, string sessionKey)
        {
            //签名验证
            var sign = EncyptHelper.ToSha1(rawData.rawData + sessionKey);
            if (sign.ToLower() != rawData.signature.ToLower())
            {
                throw new WxError("签名验证不通过");
            }

            //解密开始
            try
            {
                var user = JsonHelper.ToModel<AppUser>(EncyptHelper.AesDecrypt(rawData.encryptedData, sessionKey, rawData.iv, CipherMode.CBC));
                //水印验证
                if (user.watermark.appid != wxApp.appOption.appid)
                {
                    throw new WxError("水印验证不通过");
                }
                return user;
            }
            catch
            {

                throw new WxError("解密失败");
            }
        }

        async Task<SessionKeyInfo> IAppLogin.GetSessionKey(string code)
        {
            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={wxApp.appOption.appid}&secret={wxApp.appOption.secret}&js_code={code}&grant_type=authorization_code";
            var response = await wxApp.appBase.Get(url);
            var key = JsonHelper.ToModel<SessionKeyInfo>(response);
            return key;
        }
    }
}
